package com.sphd.education.activitys;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.sphd.education.EducationApplication;
import com.sphd.education.R;
import com.sphd.education.base.BaseActivity;
import com.sphd.education.info.EducationIntentKey;
import com.sphd.education.info.MyInfo;
import com.sphd.education.info.PushInfo;
import com.sphd.education.modle.EducationUrl;
import com.sphd.education.utils.MD5keyBean;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
/*
* 注册
* */
public class RegisterActivity extends BaseActivity {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.username)
    EditText username;
    @Bind(R.id.usernameWrapper)
    TextInputLayout usernameWrapper;
    @Bind(R.id.password)
    EditText password;
    @Bind(R.id.passwordWrapper)
    TextInputLayout passwordWrapper;
    @Bind(R.id.passwordYz)
    EditText passwordYz;
    @Bind(R.id.passwordWrapperYz)
    TextInputLayout passwordWrapperYz;
    @Bind(R.id.passwordagain)
    EditText passwordagain;
    @Bind(R.id.passwordWrapperagain)
    TextInputLayout passwordWrapperagain;
    @Bind(R.id.yanzheng_btn)
    Button yanzhengBtn;
    @Bind(R.id.register_button)
    Button registerButton;
    @Bind(R.id.yzm_linear)
    LinearLayout yzmLinear;
    private Context context;
    private boolean flag = true;
    private PushInfo pushInfo;
    private Intent intent;
    private Bundle bundle;
    private String flagForMineFragment;//用来区分是修改密码还是注册

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        initView();
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            if (result == SMSSDK.RESULT_COMPLETE) {
                // 提交验证码成功后进行网络访问
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    if (flagForMineFragment.equals("register")){
                        myNet(EducationUrl.RegisterUser);
                    }else if (flagForMineFragment.equals("forget")){
                        myNet(EducationUrl.ForgetPassword);
                    }else if (flagForMineFragment.equals("change")){
                        myNet(EducationUrl.ChangePassword);
                    }


                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    Toast.makeText(context, "验证码已发送", Toast.LENGTH_SHORT).show();
                }
            } else {
                ((Throwable) data).printStackTrace();
                Toast.makeText(context, "验证码错误", Toast.LENGTH_SHORT).show();
                yanzhengBtn.setEnabled(true);
                yanzhengBtn.setText("再次获取");


            }

        }

    };


    @Override
    public void initView() {

        context = RegisterActivity.this;
        intent = getIntent();
        bundle = intent.getBundleExtra("minefragment");
        flagForMineFragment = bundle.getString(EducationIntentKey.FLAG);
        if (flagForMineFragment.equals("register")) {
            SMSSDK.initSDK(this, "81a91d7606fc", "740f16efa4dcdbfad659688f34ac128b");
            pushInfo = DataSupport.findLast(PushInfo.class);

            usernameWrapper.setHint("手机号");
            EventHandler eh = new EventHandler() {

                @Override
                public void afterEvent(int event, int result, Object data) {

                    Message msg = new Message();
                    msg.arg1 = event;
                    msg.arg2 = result;
                    msg.obj = data;
                    handler.sendMessage(msg);
                }

            };

            SMSSDK.registerEventHandler(eh); //注册短信回调
        } else if (flagForMineFragment.equals("change")) {//修改密码进入后的界面
            getSupportActionBar().setTitle("修改密码");
            yzmLinear.setVisibility(View.GONE);
            username.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD);
            usernameWrapper.setHint("原密码");
            passwordWrapper.setHint("新密码");
            passwordWrapperagain.setHint("确认新密码");
            registerButton.setText("确认修改");
        }else if (flagForMineFragment.equals("forget")){
            getSupportActionBar().setTitle("忘记密码");
            registerButton.setText("完成");
        }

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(EducationIntentKey.REGISTERCODE, intent);
                finish();//这是自带的箭头的返回的监听
            }
        });
    }

    @Override
    public void findViewById() {

    }

    @Override
    public void myNet() {

    }


    public void myNet(String url) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                EducationUrl.HttpTitle + url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        EducationUrl.showToast(context, response);
                        if (response.equals("yes")) {
                            EducationUrl.showToast(context, "注册成功");
                            setResult(EducationIntentKey.REGISTERCODE, intent);
                            finish();//这是自带的箭头的返回的监听
                        } else if (response.equals("re")) {
                            EducationUrl.showToast(context, "存在同样手机号,注册失败");
                        } else if (response.equals("no")) {
                            EducationUrl.showToast(context, "失败");
                        }else if (response.equals("success")) {
                            EducationUrl.showToast(context, "修改成功");
                            setResult(EducationIntentKey.REGISTERCODE, intent);
                            finish();//这是自带的箭头的返回的监听
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                EducationUrl.showToast(context, error.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> map = new HashMap<String, String>();
                if(flagForMineFragment.equals("register")){
                    map.put("mobile", username.getText().toString());
                    map.put("password", new MD5keyBean().getkeyBeanofStr(password.getText().toString()));
                    if (!TextUtils.isEmpty( pushInfo.getChannelId())) {
                        map.put("channelID", pushInfo.getChannelId());
                    }else {
                        map.put("channelID", "channelID");
                    }
                }else if(flagForMineFragment.equals("change")){
                    MyInfo myInfo = (MyInfo) bundle.getSerializable("myinfo");
                    map.put("pwd", new MD5keyBean().getkeyBeanofStr(username.getText().toString()));//原密码
                    map.put("newPwd", new MD5keyBean().getkeyBeanofStr(password.getText().toString()));//新密码
                    map.put("memberId", myInfo.getUserid()+"");
                }else if (flagForMineFragment.equals("forget")){
                    map.put("mobile", username.getText().toString());
                    map.put("password", new MD5keyBean().getkeyBeanofStr(password.getText().toString()));
                }
                return map;
            }
        };
        stringRequest.setTag("registeruser");
        EducationApplication.getRequestQueue().add(stringRequest);
        EducationApplication.getRequestQueue().start();
    }

    @OnClick(R.id.yanzheng_btn)
    public void getYzmBtn() {
        getYzm();
    }

    @OnClick(R.id.register_button)
    public void setonClickRegister() {
        String usernameStr = username.getText().toString().trim();
        String userpasswordStr = password.getText().toString().trim();
        String userpasswordAgain = passwordagain.getText().toString().trim();
        String yzmStr = passwordYz.getText().toString().trim();
        if (flagForMineFragment.equals("register")) {
            //在发布程序的时候注销掉 myNet(EducationUrl.RegisterUser);------------------------
            myNet(EducationUrl.RegisterUser);
            //------------------------------------------------------------
//            if (TextUtils.isEmpty(usernameStr) || !EducationUrl.isMobileNO(usernameStr)) {
//                EducationUrl.showToast(context, "手机号填写错误");
//                return;
//            } else if (TextUtils.isEmpty(userpasswordStr) || TextUtils.isEmpty(userpasswordAgain) || !userpasswordStr.equals(userpasswordAgain)) {
//                EducationUrl.showToast(context, "两次密码不一致或未填写");
//                return;
//            } else if (TextUtils.isEmpty(yzmStr)) {
//                EducationUrl.showToast(context, "验证码为空");
//                return;
//            } else {
//
//                //短信验正式时候需要加
//                SMSSDK.submitVerificationCode("86", usernameStr, yzmStr);
//            }
        } else if (flagForMineFragment.equals("change")) {
            //在发布程序的时候注销掉 myNet(EducationUrl.ChangePassword);------------------------
            myNet(EducationUrl.ChangePassword);
            //------------------------------------------------------------
//            if (TextUtils.isEmpty(usernameStr)) {
//                EducationUrl.showToast(context, "手机号填写错误");
//                return;
//            } else if (TextUtils.isEmpty(userpasswordStr) || TextUtils.isEmpty(userpasswordAgain) || !userpasswordStr.equals(userpasswordAgain)) {
//                EducationUrl.showToast(context, "两次密码不一致或未填写");
//                return;
//            } else {
//                //短信验正式时候需要加
//                SMSSDK.submitVerificationCode("86", usernameStr, yzmStr);
//            }
        }else if (flagForMineFragment.equals("forget")){
            //在发布程序的时候注销掉 myNet(EducationUrl.ForgetPassword);;------------------------
            myNet(EducationUrl.ForgetPassword);
            //------------------------------------------------------------
//            if (TextUtils.isEmpty(usernameStr) || !EducationUrl.isMobileNO(usernameStr)) {
//                EducationUrl.showToast(context, "手机号填写错误");
//                return;
//            } else if (TextUtils.isEmpty(userpasswordStr) || TextUtils.isEmpty(userpasswordAgain) || !userpasswordStr.equals(userpasswordAgain)) {
//                EducationUrl.showToast(context, "两次密码不一致或未填写");
//                return;
//            } else if (TextUtils.isEmpty(yzmStr)) {
//                EducationUrl.showToast(context, "验证码为空");
//
//                return;
//            } else {
//                //短信验正式时候需要加
//                SMSSDK.submitVerificationCode("86", usernameStr, yzmStr);
//            }
        }


    }

    private void getYzm() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);
        alertDialogBuilder
                .setTitle("手机号码确认")
                .setMessage("我们将发送验证码短信到这个号码:\n" + username.getText().toString().trim()
                        + "请注意查收")
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // get user input and set it to result
                                // edit text
                                SMSSDK.getVerificationCode("86",
                                        username.getText().toString().trim());
                                countdown js = new countdown(flag, yanzhengBtn);
                                js.execute();
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                dialog.cancel();
                            }
                        });
        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            setResult(EducationIntentKey.REGISTERCODE, intent);
            finish();//这是自带的箭头的返回的监听
            //do something...
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 手机验证码的类
     */
    class countdown extends AsyncTask<Void, String, Void> {

        private boolean flag = true;
        private Button getCheckCode;

        public countdown(boolean flag, Button getCheckCode) {
            this.flag = flag;
            this.getCheckCode = getCheckCode;
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            long fur = System.currentTimeMillis() + 60000;

            while (flag) {
                long now = System.currentTimeMillis();
                long cha = fur - now;
                publishProgress("请稍后 : " + (cha / 1000));
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (cha < 0) {
                    publishProgress("获取验证码");
                    flag = false;
                }

            }

            return null;
        }

        @Override
        protected void onProgressUpdate(String... progresses) {
            getCheckCode.setText(progresses[0]);
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            getCheckCode.setClickable(true);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            getCheckCode.setClickable(false);
        }

    }

}
